package netty.lora;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.UnsupportedEncodingException;
import java.util.concurrent.TimeUnit;

/**
 * lora设备模拟器
 *
 * @Author zhangtao
 * @create 2021/11/2 9:19
 */
@Slf4j
public class LoraMonitor {
    private String ip;
    private int port;

    public LoraMonitor(String ip, int port) {
        this.ip = ip;
        this.port = port;
    }

    public void monitor() {
        LoraMonitor self = this;
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        Bootstrap bs = new Bootstrap();
        bs.group(bossGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast(new LoraEncoder());
                        socketChannel.pipeline().addLast(new LoraDecoder());
                        // 处理来自服务端的响应信息
                        socketChannel.pipeline().addLast(new LoraDataHandler(self));
                    }
                });

        // 连接
        ChannelFuture channelFuture = bs.connect(ip, port);
        //客户端断线重连逻辑
        channelFuture.addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    log.info("连接Netty服务端成功...");
                } else {

                    log.info("连接Netty服务端失败，进行断线重连...");
                    final EventLoop loop = future.channel().eventLoop();
                    loop.schedule(new Runnable() {
                        @SneakyThrows
                        @Override
                        public void run() {
                            log.info("连接正在重试...");
                            monitor();
                        }
                    }, 20, TimeUnit.SECONDS);
                }
            }
        });

        try {
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws UnsupportedEncodingException, InterruptedException {
        new LoraMonitor("127.0.0.1", 9003).monitor();
    }
}
